package com.hou.utils;

import com.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shkstart
 * @create 2021-09-04-15:26
 */
@Component
public class HtmlParseUtil {


    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().parseJd("java").forEach(System.out::println);
    }

    public List<Content> parseJd(String keywords) throws IOException {
        //获取请求  https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword=" + keywords;

        //解析网页
        Document document = Jsoup.parse(new URL(url), 30000);

        //获取标签id
        Element element = document.getElementById("J_goodsList");


        //获取所有li元素
        Elements elements = element.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();

        //获取元素中的内容
        for (Element el : elements) {
            // 很多网页采用懒加载机制,使用下面这种方式无法获取真实图片
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
            goodsList.add(content);

        }
        return goodsList;
    }

}
